package com.fjnu.dao.impl;

import com.fjnu.dao.CategoryDao;
import com.fjnu.domain.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CategoryDaoImpl implements CategoryDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Category category) {
        if (category == null || category.getName() == null || category.getName().trim().isEmpty()) {
            return 0;
        }

        String sql = "INSERT INTO tb_category(name, `order`, parent_id, create_time, update_time) " +
                "VALUES(?, ?, ?, NOW(), NOW())";
        return jdbcTemplate.update(sql,
                category.getName(),
                category.getOrder(),
                category.getParentId()
        );
    }

    @Override
    public int delete(Integer categoryId) {
        if (categoryId == null) {
            return 0;
        }
        String sql = "DELETE FROM tb_category WHERE id = ?";
        return jdbcTemplate.update(sql, categoryId);
    }

    @Override
    public List<Category> selectAll() {
        String sql = "SELECT * FROM tb_category ORDER BY `order` ASC, create_time DESC";
        List<Category> categories = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Category.class));
        return categories.isEmpty() ? null : categories;
    }

    @Override
    public Category selectById(Integer categoryId) {
        if (categoryId == null) {
            throw new IllegalArgumentException("分类ID不能为空");
        }
        String sql = "SELECT * FROM tb_category WHERE id = ?";
        List<Category> categories = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Category.class), categoryId);
        return categories.isEmpty() ? null : categories.get(0);
    }

    @Override
    public Category selectByName(String name) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("分类名称不能为空");
        }
        String sql = "SELECT * FROM tb_category WHERE name = ?";
        List<Category> categories = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Category.class), name.trim());
        return categories.isEmpty() ? null : categories.get(0);
    }
}